package com.basiclib.base

//import org.greenrobot.eventbus.EventBus
import android.content.Context
import android.os.Bundle
import android.os.Looper
import androidx.fragment.app.Fragment
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.inputmethod.InputMethodManager
import com.basiclib.inter.IMvpView
import com.basiclib.inter.IPresenter
import com.basiclib.lifecycle.FragmentLifecycleable
import com.basiclib.utils.*
import com.basiclib.utils.eventbus.EventBusMessage
import com.basiclib.view.ProgressDialog
import com.basiclib.view.SnackbarUtil
import com.basiclib.widget.OnDialogDismissListener
import com.trello.rxlifecycle2.android.FragmentEvent
import com.umeng.analytics.MobclickAgent
import io.reactivex.subjects.BehaviorSubject
import io.reactivex.subjects.Subject
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.EventBus.TAG
import org.greenrobot.eventbus.Subscribe
import org.jetbrains.anko.runOnUiThread
import org.jetbrains.anko.toast

abstract class BaseFragment<P : IPresenter<*>> : androidx.fragment.app.Fragment(), IMvpView, FragmentLifecycleable {
    var mobclickAgentCode: String? = null//埋点编号
    lateinit var mContext: Context
    lateinit var mActivity: BaseActivity
    var visible: Boolean = false
    var prepared:Boolean = false
    var progressDialog:ProgressDialog = ProgressDialog()

    private val behaviorSubject = BehaviorSubject.create<FragmentEvent>()
    override fun provideLifecycleSubject(): Subject<FragmentEvent> = behaviorSubject
    protected var rootView: View? = null
    override fun onAttach(context: Context) {
        super.onAttach(context)
        mContext = context
        mActivity = activity as BaseActivity
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        onFragmentInject()
        attachView()
    }

    fun showLoadingDialog() {

        if (progressDialog.getTag() == null) {
            progressDialog.show(activity!!.supportFragmentManager, "progress")
        }
    }

    fun dismissLoadingDialog() {
        if (progressDialog != null) {
            progressDialog.dismiss()
        }

    }



    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        if (rootView == null) {
            //            progressDialog = new ProgressDialog();
            rootView = inflater.inflate(setViewId(), container, false)
            if (!EventBus.getDefault().isRegistered(this)) {
                EventBus.getDefault().register(this)
            }

        }
//        var parent = rootView!!.getParent() as ViewGroup
//        if(parent!=null){
//            parent.removeView(rootView)
//        }
        return rootView
    }


    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        initView()
        initData()
        setListener()
    }
    protected abstract fun onFragmentInject()
    protected abstract fun attachView()
    protected abstract fun initView()
    protected abstract fun initData()
    protected abstract fun setViewId(): Int
    protected  abstract fun doOnVisible()
    protected abstract fun doOnInvisible()

    override fun setListener() {}



    override fun isNetWorkAvailable(): Boolean = isNetworkAvaliable(activity)

    override fun showLoading() {
    }

    override fun hideLoading() {
    }

    override fun showErrorView() {
    }
    override fun showLoading(msg: String, error: String, listener: OnDialogDismissListener?) {
        showLoading(mContext, msg, errorMsg = error, listener = listener)
    }

    override fun showErrorLoading(error: String, listener: OnDialogDismissListener?) {
        showLoading(mContext, status = STATUS_ERROR, errorMsg = error)
    }

    override fun showSucessLoading(msg: String, listener: OnDialogDismissListener?) {
        showLoading(mContext, msg = msg, status = STATUS_SUCESS)
    }

    fun showLoading(
        ctx: Context,
        msg: String = "",
        status: Int = STATUS_LOADING,
        errorMsg: String = "",
        tag: Int = -1,
        listener: OnDialogDismissListener? = null
    ) {
        DialogManager.instance().showProgressBarDialog(ctx, msg, status, errorMsg, tag, listener)
    }
    override fun showShortToast(msg: String) {
        if (Looper.myLooper() != Looper.getMainLooper()) {
            mContext.runOnUiThread { toast(msg) }
        } else {
            mContext.toast(msg)
        }
    }


    fun showShortToast(message: String, type: Int) {
        val imm = activity!!.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
        imm?.hideSoftInputFromWindow(activity!!.window.decorView.windowToken, 0)
        SnackbarUtil.showBarShortTime(activity!!.findViewById(android.R.id.content), message, type)
    }

    override fun onDestroyView() {
        super.onDestroyView()
        EventBus.getDefault().unregister(this)
    }


    override fun setUserVisibleHint(isVisibleToUser: Boolean) {
        super.setUserVisibleHint(isVisibleToUser)
        visible = userVisibleHint
        if (!prepared || !isVisible) {
            return
        }
        if (prepared) {
            if (userVisibleHint) {
                visible = true
                doOnVisible()
            } else {
                visible = false
                doOnInvisible()
            }
        }

    }

    /**
     * 埋点事件
     *
     * @param eventId 事件编号
     */
    fun mobclickAgentEvent(eventId: String) {
        MobclickAgent.onEvent(activity, eventId)
    }

    @Subscribe
    fun onEventMainThread(eventBusMessage: EventBusMessage) {
        Log.i(TAG, "onEventMainThread: " + eventBusMessage.toString())
    }

}